package com.hn.kiss.config.compoent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日期转换类
 * 将标准日期、标准日期时间、时间戳转换成Date类型
 */
/*@Deprecated*/
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private Logger logger = LoggerFactory.getLogger(LocalDateTimeConverter.class);

    private static final String dateFormat1 = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    @Override
    public LocalDateTime convert(String value) {
        logger.info("转换日期：" + value);
        if(value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
            return null;
        }

        value = value.trim();

        try {
            DateTimeFormatter formatter;
            if (value.contains("T")) {
                return LocalDateTime.parse(value);
            }else if(value.contains(" ")){
                formatter = DateTimeFormatter.ofPattern(dateFormat1);
                return LocalDateTime.parse(value, formatter);
            }else {
                formatter = DateTimeFormatter.ofPattern(shortDateFormat);
                LocalDate parse = LocalDate.parse(value, formatter);
                return parse.atStartOfDay();
            }

        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
    }
}

